package cn.enjoy.design.behavior.observe.manager;

import cn.enjoy.design.behavior.observe.event.Event;
import cn.enjoy.design.behavior.observe.event.EventType;
import cn.enjoy.design.behavior.observe.listener.Listener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author K
 * @date 2021/11/17 14:25
 */
public class Manager {

    private final Map<Enum<EventType>, List<Listener<Event>>> map = new HashMap<>();


    public void subscribe(Listener<Event> listener) {
        EventType eventType = listener.getEventType();
        if (map.containsKey(eventType)) {
            List<Listener<Event>> listenerList = map.get(eventType);
            if (!listenerList.contains(listener)) {
                listenerList.add(listener);
            }
        } else {
            ArrayList<Listener<Event>> list = new ArrayList<>();
            list.add(listener);
            map.put(eventType, list);
        }
    }

    public void handle(Event event) {
        map.get(event.getEventType()).forEach(x -> {x.handle(event);});
    }

}
